package by.ostrovsky.webhousingsystem.crypt;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

import by.ostrovsky.webhousingsystem.exception.OperationErrorException;
import sun.misc.BASE64Encoder;

public final class SHACrypt {
	private static volatile SHACrypt instance;
	private static Logger logger = Logger
			.getLogger(SHACrypt.class);

	public SHACrypt() {
	}

	public synchronized String encrypt(String string) throws OperationErrorException {

		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("SHA");
		} catch (NoSuchAlgorithmException e) {
			logger.error(e);
			throw new OperationErrorException();
		}
		try {
			messageDigest.update(string.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			logger.error(e);
			throw new OperationErrorException();
		}
		byte raw[] = messageDigest.digest();
		String hash = (new BASE64Encoder()).encode(raw);
		return hash;
	}

	public static SHACrypt getInstance() {
		if (instance == null)
			synchronized (SHACrypt.class) {
				instance = new SHACrypt();
			}
		return instance;
	}
	
	public static Boolean destroy(){
		instance = null;
		if(instance == null)
			return true;
		return false;
	}
}
